package com.taotao.delayjob.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 *
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2024/7/17 14:54
 */
@Slf4j
public class RetryTaskHub implements ApplicationContextAware, InitializingBean {
    private static ApplicationContext applicationContext;

    private ConcurrentHashMap<String, IRetryHandler> retryHanderMap = new ConcurrentHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, Object> serviceBeanMap = applicationContext.getBeansWithAnnotation(RetryHandler.class);
        if (serviceBeanMap != null && serviceBeanMap.size() > 0) {
            for (Object serviceBean : serviceBeanMap.values()) {
                if (serviceBean instanceof IRetryHandler) {
                    String name = serviceBean.getClass().getAnnotation(RetryHandler.class).value();
                    IRetryHandler handler = (IRetryHandler) serviceBean;
                    if (retryHanderMap.get(name) != null) {
                        throw new RuntimeException("RetryHandler[" + name + "] naming conflicts.");
                    }
                    retryHanderMap.put(name, handler);
                    log.info(">>>>>> register  RetryHandler {}-{} success ", name, handler.getClass().getName());
                }
            }
        }

        log.info(">>>>>> register  RetryHandler   over!! ");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }


    public IRetryHandler getRetryHandler(String busiCode) {
        return retryHanderMap.get(busiCode);
    }

}
